﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Gfw.Models.Stock;
using Gfw.Repository;
using NHibernate.Criterion;

namespace Gfw.Repositories.Stock
{
    public class BargainRecordRepository : Repository<StkBargainrecord>
    {
        public int QueryCount(string userId, DateTime? startDate, DateTime? endDate)
        {
            var cri = Session.CreateCriteria(typeof(StkBargainrecord)).Add(Expression.Eq("Userid", userId));
            if (startDate.HasValue)
            {
                cri.Add(Expression.Ge("BargainDate", startDate));
            }
            if (endDate.HasValue)
            {
                cri.Add(Expression.Lt("BargainDate", endDate.Value.AddDays(1)));
            }

            var hql = "select count(*) from  StkBargainrecord where Userid=:userId";
            if (startDate.HasValue)
                hql += "  and BargainDate>=:startDate";
            if (endDate.HasValue)
                hql += " and BargainDate<:endDate";
            hql += " order by BargainDate desc";


            var query = Session.CreateQuery(hql).SetString("userId", userId);
            if (startDate.HasValue)
                query = query.SetDateTime("startDate", startDate.Value);
            if (endDate.HasValue)
                query = query.SetDateTime("endDate", endDate.Value.AddDays(1));
            return (int) query.UniqueResult<long>();
        }

        public IList<StkBargainrecord> Query(string userId, DateTime? startDate, DateTime? endDate,
            int rowStart, int pageSize)
        {
            var hql = "from  StkBargainrecord where Userid=:userId ";
            if (startDate.HasValue)
                hql += "  and BargainDate>=:startDate";
            if (endDate.HasValue)
                hql += " and BargainDate<:endDate";
            hql += " order by BargainDate desc";
            var query = Session.CreateQuery(hql).SetString("userId", userId);
            if (startDate.HasValue)
                query = query.SetDateTime("startDate", startDate.Value);
            if (endDate.HasValue)
                query = query.SetDateTime("endDate", endDate.Value.AddDays(1));
            query = query.SetFirstResult(rowStart).SetMaxResults(pageSize);
            return query.List<StkBargainrecord>();
        }


        /// <summary>
        /// 计算股票日成交量
        /// </summary>
        /// <param name="day"></param>
        /// <returns></returns>
        public decimal TendencyCountByDay(DateTime day)
        {
            var hql =
                "select sum(ActualCount) from StkBargainrecord where BargainType =0 and BargainDate>=:start and BargainDate<:end";
            var query = Session.CreateQuery(hql).SetDateTime("start", day)
                .SetDateTime("end", day.AddDays(1)).UniqueResult<long>();
            return query;
        }
    }
}
